package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 处理参数校验异常（手机号格式错误等）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result> handleDtoValidationError(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("DTO 参数校验失败：{}", errorMsg);
        Result result = Result.error(errorMsg).setCode(0);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }

    /**
     * 处理业务异常：设置HTTP状态码为异常中定义的httpStatus
     */
    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(BaseException ex) {
        log.error("业务异常：{}", ex.getMessage());
        Result result = Result.error(ex.getMessage());
        // 关键：通过ResponseEntity设置HTTP响应状态码
        return ResponseEntity.status(ex.getHttpStatus()).body(result);
    }

    /**
     * 处理SQL异常：设置HTTP状态码409（冲突）
     */
    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        String msg;
        if (message.contains("Duplicate entry")){
            String username = message.split(" ")[2];
            msg = username + MessageConstant.ALREADY_EXISTS;
        } else {
            msg = MessageConstant.UNKNOWN_ERROR;
        }
        Result result = Result.error(msg);
        return ResponseEntity.status(409).body(result); // SQL冲突返回409
    }
}
